<template>
  <div id='firmware-update'>
    <!-- 搜索栏 -->
    <!-- <div class="search-box"> -->
      <Row type='flex' justify="space-between" style="padding: 20px">
        <Row type='flex' align='middle'>
          <!-- <Col class="search-item"><span>门店名称：</span><Input placeholder="请输入" :maxlength="20" v-model='inputValue' style="width:180px" /></Col> -->
          <Col style="margin-right:8px"><span>门店名称：</span></Col>
          <Col>
            <Select v-model="inputValue" filterable :clearable='true' @on-change='changeStore' @on-clear='search'>
              <Option v-for="item in storeList" :value="item.shopName" :key="item.shopId">{{ item.shopName }}</Option>
            </Select>
          </Col>
          <Col><Button type="primary" class="draw-btn" @click="search" style="margin-left: 24px;width:80px">查询</Button></Col>
        </Row>
        <Col><Button @click="allSet">批量设置</Button></Col>
      </Row>
    <!-- </div> -->
    <!-- table栏 -->
    <Table stripe :columns="columns" :data="tableData" class="table-list" :height="tableHeight" :loading='loading'>
      <template slot-scope="{ row }" slot="soltCount">
        <span class="special" @click="skipSlit(row,'1')">{{row.soltCount}}</span>
      </template>
      <template slot-scope="{ row }" slot="undoCount">
        <span class="special" @click="skipSlit(row,'0')">{{row.undoCount}}</span>
      </template>
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys iconsetting" @click="viewHistory('1',row)" title="设置"></i>
        <i class="iconsys iconzhongqi" title="重启" @click="restart(row.orgId)"></i>
        <i class="iconsys iconlishijilu" @click="viewHistory('2',row)" title="历史记录"></i>
      </template>
    </Table>
    <!-- 分页 -->
    <Row type='flex' justify="end" style="padding:20px">
      <Col>
        <Page :total="pageObj.total"
            :current="pageObj.pageIndex"
            :page-size="pageObj.pageSize"
            show-sizer
            show-total
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <!-- 批量设置组件 -->
    <select-shop :checkdList="checkdList" :titleObj='titleObj'
      :dataTree="dataTree"
      :modalShow="modalShow"
      @oncancel="selctshopCancel"
      @selctshop="volumeSet"
      v-if="modalShow"></select-shop>
    <!-- 二次modal弹框 -->
    <Modal
        v-model="setModalStatus"
        :transfer='false'
         :closable='true'
         :mask-closable='false'
         @on-cancel="cancelModal"
        title="设置配置项">
        <Row>
          <Col>
            <Form ref="firmwareFormValidate" :model="firmwareFormValidate" :rules="firmwareRuleValidate" :label-width="100">
              <FormItem label="目标版本：" prop="firmwareVersion">
                <Select v-model="firmwareFormValidate.firmwareVersion" style="width:260px">
                  <Option v-for="item in versionList" :value="item" :key="item">{{ item }}</Option>
                </Select>
              </FormItem>
            </Form>
          </Col>
        </Row>
        <div slot="footer">
          <Button style="margin-right:10px;width:80px" @click="skipPrevious">上一步</Button>
          <Button type="primary" style='width:80px' @click="allPublic">确定</Button>
        </div>
    </Modal>
    <!-- 侧边栏弹窗--设置与历史记录 -->
    <Drawer :title="drawTitle" :closable="true" width='640' :transfer='false' v-model="openDraw" class="history-draw">
      <Row type='flex' justify="center" style="padding-top:50px;border-top: 1px solid #e8eaec;" v-if="drawTitle === '固件升级设置'">
        <Col>
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">
            <FormItem label="门店名称：" prop="shopName">
              <Input placeholder="门店名称" v-model='formValidate.shopName' style="width:260px" :disabled='true' />
            </FormItem>
            <FormItem label="目标版本：" prop="firmwareTarget">
              <!-- <Input placeholder="目标版本号" v-model='formValidate.firmwareTarget' style="width:260px" /> -->
              <Select v-model="formValidate.firmwareTarget" style="width:260px">
                <Option v-for="item in versionList" :value="item" :key="item">{{ item }}</Option>
              </Select>
            </FormItem>
          </Form>
        </Col>
      </Row>
      <div v-if="drawTitle === '历史记录'">
        <Table stripe :columns="columnsHistory" :data="tableHistoryData" :height='getHistoryTableHeight' class='table-list'></Table>
      </div>
      <div class="demo-drawer-footer">
        <Row type='flex' justify="end" v-if="drawTitle === '历史记录'">
          <Col>
          <Page :total="historyObj.total"
              :current="historyObj.pageIndex"
              :page-size="historyObj.pageSize"
              show-sizer
              show-total
              @on-change='changeHistoryPageIndex'
              @on-page-size-change='changeHistoryPageSize' />
          </Col>
        </Row>
        <div v-if="drawTitle === '固件升级设置'">
          <Button style="margin-right: 20px" class="draw-btn" @click="openDraw = false">取消</Button>
          <Button type="primary" class="draw-btn" @click="sureSetMertail" :disabled='isDisabled'>确定</Button>
        </div>
      </div>
    </Drawer>
  </div>
</template>

<script>
import { iterationFirmwareList, iterationHistoryList, shopRestart, lookTargetFirmware, setDicSave, getDicQuery } from '@/api/setting'
import { getShopList } from '@/api/system/store'
import SelectShop from '@/view/components/select-machine/select-machine.vue'
import volumeStore from '@/view/setting/components/own-use/volumeStore'
import mixins from '@/view/setting/components/own-use/mixins'
export default {
  name: 'global_setting_page_22',
  mixins: [mixins, volumeStore],
  components: {
    SelectShop
  },
  computed: {
    tableHeight () {
      let height = this.tableData.length > 10 ? 520 : 0
      return height
    },
    getHistoryTableHeight () {
      let height = 0
      if (this.tableHistoryData.length > 10) {
        height = (document.documentElement.clientHeight || document.body.clientHeight) - 103
      } else {
        height = 0
      }
      return height
    }
  },
  data () {
    return {
      isDisabled: false,
      loading: true,
      orgId: '',
      shopId: '',
      drawTitle: '固件升级设置',
      inputValue: '',
      storeList: [], // 门店列表
      openDraw: false,
      formValidate: {
        shopName: '',
        firmwareTarget: ''
      },
      ruleValidate: {
        shopName: { required: true, message: '门店名称不能为空', trigger: 'change' },
        firmwareTarget: { required: true, message: '目标版本不能为空', trigger: 'change' }
      },
      firmwareFormValidate: {
        firmwareVersion: ''
      },
      firmwareRuleValidate: {
        firmwareVersion: { required: true, message: '目标版本不能为空', trigger: 'change' }
      },
      versionList: [],
      tableData: [],
      tableHistoryData: [],
      columnsHistory: [
        {
          title: '发布时间',
          key: 'createTime',
          width: 180
        },
        {
          title: '起始版本',
          key: 'extra'
        },
        {
          title: '目标版本',
          key: 'configValue'
        },
        {
          title: '操作人',
          key: 'creatorName',
          width: 160
        }
      ],
      columns: [
        {
          title: '门店名称',
          key: 'orgName'
        },
        {
          title: '机台总数',
          key: 'machineInstanceCount'
        },
        {
          title: '投币口数量',
          slot: 'soltCount'
        },
        {
          title: '当前版本',
          key: 'currentVersions'
        },
        {
          title: '未升级数量',
          slot: 'undoCount'
        },
        {
          title: '操作时间',
          key: 'operTime'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ]
    }
  },
  methods: {
    volumeSet (val) {
      this.setModalStatus = true
      this.modalShow = false
      this.checkdList = val
      // 此处请求选择好门店后，设置固件
      this.getTargetList()
    },
    restart (shopId) {
      // this.$emit('restart', shopId)
      if (shopId) {
        shopRestart({
          shopId: shopId
        }).then(res => {
          if (res.data.status === 200) {
            this.$Message.success('重启成功！')
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      } else {
        this.$Message.error('门第id不能为空')
      }
    },
    allPublic () {
      this.$refs.firmwareFormValidate.validate((valid) => {
        if (valid) {
          let arr = this.checkdList.map(item => {
            return item.id
          })
          setDicSave({
            msType: '1',
            merchantId: this.$store.state.user.merchantId,
            targetFirmwareVersion: this.firmwareFormValidate.firmwareVersion,
            shopIds: arr
          }).then(res => {
            if (res.data.status === 200) {
              this.$Message.success('设置成功！')
              this.setModalStatus = false
              this.getData()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    search () {
      this.pageObj.pageIndex = 1
      this.getData()
    },
    changeHistoryPageIndex (index) {
      this.historyObj.pageIndex = index
      this.getHistoryList()
    },
    changeHistoryPageSize (size) {
      this.historyObj.pageSize = size
      this.historyObj.pageIndex = 1
      this.getHistoryList()
    },
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    viewHistory (type, row) {
      this.openDraw = true
      this.orgId = row.orgId
      if (type === '1') {
        this.drawTitle = '固件升级设置'
        this.formValidate.shopName = row.orgName
        lookTargetFirmware().then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            this.versionList = result.data || []
            if (this.versionList.length > 0) {
              this.searchSingleSet()
            }
          } else {
            this.$Message.error(`${result.error}`)
          }
        })
      } else {
        this.drawTitle = '历史记录'
        this.getHistoryList()
      }
    },
    // 查询单个设置
    searchSingleSet () {
      getDicQuery({
        shopId: this.orgId,
        'dictKeys': 'targetFirmwareVersion',
        'merchantId': this.$store.state.user.merchantId,
        'msType': '1'
      }).then(res => {
        if (res.data.status === 200) {
          let ele = res.data.data[0].targetFirmwareVersion
          if ((ele !== '0' || ele !== 0) && ele) {
            this.versionList.forEach(item => {
              if (item === ele) {
                this.formValidate.firmwareTarget = ele
              }
            })
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    skipSlit (row, type) {
      this.$router.push({ name: 'firmware_slit', query: { shopName: row.orgName, shopId: row.orgId, type: type } })
    },
    sureSetMertail () {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          this.isDisabled = true
          setTimeout(() => {
            setDicSave({
              msType: '1',
              merchantId: this.$store.state.user.merchantId,
              targetFirmwareVersion: this.formValidate.firmwareTarget,
              shopIds: [this.orgId]
            }).then(res => {
              this.isDisabled = false
              if (res.data.status === 200) {
                this.$Message.success('设置成功！')
                this.openDraw = false
                this.getData()
              } else {
                this.$Message.error(`${res.data.error}`)
              }
            })
          }, 200)
        }
      })
    },
    changeStore () {
      this.pageObj.pageIndex = 1
      this.getData()
    },
    // 获取目标版本列表
    getTargetList () {
      lookTargetFirmware().then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.versionList = result.data || []
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    },
    // 获取门店列表
    chooseShopList () {
      getShopList({ 'merchantId': this.$store.state.user.merchantId, offset: '0', limit: '5000' }).then(res => {
        if (res.data.status === 200) {
          this.storeList = res.data.data
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch((err) => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取历史记录
    getHistoryList () {
      iterationHistoryList({
        merchantId: this.$store.state.user.merchantId,
        belongId: this.orgId,
        configKey: 'targetFirmwareVersion',
        offset: this.historyObj.pageSize * (this.historyObj.pageIndex - 1),
        limit: this.historyObj.pageSize
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.tableHistoryData = result.data || []
          this.historyObj.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    },
    // 获取升级包与回退包列表
    getData () {
      this.loading = true
      iterationFirmwareList({
        merchantId: this.$store.state.user.merchantId,
        shopName: this.inputValue,
        // shopId: this.shopId,
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data || []
          this.pageObj.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    }
  },
  mounted () {
    this.chooseShopList()
    this.getData()
  }
}
</script>

<style lang='less'>
  #firmware-update {
    .ivu-radio-group-button .ivu-radio-wrapper-checked:first-child {
      color: #fff;
      background: #2d8cf0;
    }
    .ivu-radio-group-button .ivu-radio-wrapper-checked {
      color: #fff;
      background: #2d8cf0;
    }
    .table-list {
      .special {
        color: #2D8CF0;
        cursor: pointer;
      }
    }
    .draw-btn {
      width: 72px;
    }
    .ivu-drawer-body {
      padding: 0;
    }
    .ivu-drawer-header {
      border-bottom: 0;
    }
    .demo-drawer-footer {
      width: 640px;
      position: absolute;
      bottom: 0;
      right: 0;
      border-top: 1px solid #e8e8e8;
      padding: 10px 16px;
      text-align: right;
      background: #fff;
    }
  }
</style>
